package com.huawei.hwclouds.lubanops.demo.common.util;

import java.util.HashMap;
import java.util.Map;

import com.huawei.hwclouds.lubanops.demo.common.exception.common.ParameterException;
import org.apache.commons.lang3.StringUtils;

/**
 * 实现二进制和字符串能相互转换的util方法，主要是转换成 下面数组指定的字符，转换后字节长度加倍
 *
 * @author y00438022
 * @since 2020/5/11
 **/
public class StringUtil {
    private static final char[] HEX_DIGITS = {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
    };

    private static Map<Integer, Byte> charMap = new HashMap<Integer, Byte>();

    static {

        for (int i = 0; i < HEX_DIGITS.length; i++) {
            charMap.put((int) HEX_DIGITS[i], (byte) i);
        }
    }

    /**
     * 二进制转成可见字符串
     *
     * @param bytes
     * @return
     */
    public static String bytesToString(byte[] bytes) {
        int j = bytes.length;
        char[] str = new char[j * 2];
        int k = 0;
        for (int i = 0; i < j; i++) {
            byte byte0 = bytes[i];
            str[k++] = HEX_DIGITS[byte0 >>> 4 & 0xf];
            str[k++] = HEX_DIGITS[byte0 & 0xf];
        }

        return new String(str);
    }

    /**
     * 字符串转成二进制
     *
     * @param s
     * @return
     */
    public static byte[] stringToBytes(String s) {

        char[] chars = s.toCharArray();
        if (chars.length % 2 != 0) {
            throw new ParameterException("wrong input:" + s);
        }

        byte[] result = new byte[chars.length / 2];
        for (int i = 0; i < result.length; i++) {
            char k = chars[i * 2];
            Byte high = charMap.get((int) k);
            if (high == null) {
                throw new ParameterException("wrong input:" + s);
            }

            Byte low = charMap.get((int) chars[i * 2 + 1]);
            if (low == null) {
                throw new ParameterException("wrong input:" + s);
            }

            int x = (byte) (high << 4); //高四位
            byte v = (byte) (x + low); //高低相加
            result[i] = v;
        }
        return result;
    }

    public static String clearString(String string) {
        if (StringUtils.isBlank(string)) {
            return "";
        }
        return string.replace("\n", "").replace("\r", "");
    }

}
